﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using DAL;
using System.Data;
using System.Data.SqlClient;

public partial class Thanh_Toan : System.Web.UI.Page
{
    DigitalWorldDataContext db = new DigitalWorldDataContext();
    OrdersBLL or = new OrdersBLL();
    OrderDetailsBLL od = new OrderDetailsBLL();
    string connectionString = WebConfigurationManager.ConnectionStrings["DAL.Properties.Settings.DigitalWorldConnectionString"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dtCart = Session["Cart"] as DataTable;
            HttpCookie ck = Request.Cookies["www.digital.com"];
            if (dtCart.Rows.Count == 0)
                Response.Redirect("~/Default.aspx");

            if (Session["Username"] == null)
            {
                if (ck == null)
                    Response.Redirect("~/Default.aspx");
                else
                {
                    Session["Username"] = ck["Username"];
                    pnCart.Visible = false;
                    LoadData();
                    LoadCountItem();
                }
            }
            else
            {
                pnCart.Visible = false;
                LoadData();
                LoadCountItem();
            }
            loadPayment();
        }
    }
    void LoadCountItem()
    {
        DataTable dtCart = Session["Cart"] as DataTable;
        if (dtCart.Rows.Count > 0)
        {
            lbSelected.Text = dtCart.Compute("SUM(Quantity)", "").ToString() + " item(s)";
        }
    }
    void loadPayment()
    {
        ddl_payment.DataSource = db.payments;
        ddl_payment.DataTextField = "paymentname";
        ddl_payment.DataValueField = "paymentid";
        ddl_payment.DataBind();
    }



    //void InsertOrderdetail(order o)
    //{
    //    SqlConnection cnn = new SqlConnection("server=.; database=DigitalWorld; uid=sa; pwd=123");
    //    SqlDataAdapter da = new SqlDataAdapter("select MAX(orderid) as MAX from Orders", cnn);
    //    DataTable dt = new DataTable();
    //    da.Fill(dt); cnn.Close();
        
    //    DataTable dtCart = Session["Cart"] as DataTable;
    //    for (int i = 0; i < dtCart.Rows.Count; i++)
    //    {
    //        DataRow r = dtCart.Rows[i];
    //        //orderdetail od_ = new orderdetail
    //        //{
    //       int     orderid =int.Parse( dt.
    //          int  productid = int.Parse(r["ProductID"].ToString());
    //          double  unitprice = double.Parse(r["Unitprice"].ToString());
    //           int quantity = int.Parse(r["Quantity"].ToString());
    //           int discount = 0;
    //        //};
    //        //od.OrderDetail(od_);
    //    }

    void LoadData()
    {
        DataTable dtCart = Session["Cart"] as DataTable;
        gv_InformationCart.DataSource = dtCart;
        gv_InformationCart.DataBind();

        if (dtCart.Rows.Count == 0)
            return;
        else
        {
            gv_InformationCart.FooterRow.Cells[3].Text = "Tổng tiền";
            gv_InformationCart.FooterRow.Cells[4].Text = double.Parse(dtCart.Compute("Sum(TotalAmount)", "").ToString()).ToString("#,###,###") + " VNĐ";
        }

    }

    protected void btnPayment_Click(object sender, EventArgs e)
    {
        try
        {
            order o = new order
            {
                customerid = int.Parse(Session["ID"].ToString()),
                employeeid = null,
                orderdate = DateTime.Now.Date,
                requireddate = DateTime.Parse(txtRequiredDate.Text),
                vat = 10,
                shipname = txtShipname.Text,
                shipaddress = txtShipname.Text,
                freight = 10000,
                shipcity = txtShipcity.Text,
                shippostalcode = txtShipPostalCode.Text,
                shipcountry = txtShipCountry.Text
            };
            or.Order_Insert(o);
            //InsertOrderdetail(o);
            //vi du dropdownlist ddltext.DataTextField="ten cot";
            pnCart.Visible = true;
            this.reset();
            lblThongBao.Text = "Chúng tôi đã sẽ kiểm tra hóa đơn thanh toán của bạn và giao hàng đúng thời giạn mà bạn yêu cầu.";
        }
        catch
        {
            lblThongBao.Text = "Thất bại";
        }
    }
    void reset() {
        txtShipname.Text = String.Empty;
        txtShipCountry.Text = String.Empty;
        txtShipcity.Text = String.Empty;
        txtShipPostalCode.Text = String.Empty;
        txtRequiredDate.Text = String.Empty;
    }
    protected void btnThanhToan_Click(object sender, EventArgs e)
    {
        try
        {
            var danhsach = db.sp_SelectOneOrder().First();
            int ordeid = danhsach.MAX.Value;
            DataTable dtCart = Session["Cart"] as DataTable;
            for (int i = 0; i < dtCart.Rows.Count; i++)
            {
                DataRow r = dtCart.Rows[i];
                orderdetail od_ = new orderdetail
                {
                    productid = int.Parse(r["ProductID"].ToString()),
                    unitprice = decimal.Parse(r["Unitprice"].ToString()),
                    quantity = int.Parse(r["Quantity"].ToString()),
                    discount = 0,
                };
                od.OrderDetail(ordeid,od_);
            }
            decimal amount=decimal.Parse(dtCart.Compute("Sum(TotalAmount)", "").ToString());
            var ds2=db.orders.Where(o1=>o1.orderid==ordeid).First();
            decimal totalamount = amount + ds2.freight.Value + ((amount*ds2.vat.Value)/100);
            db.sp_OrderUpdateTotalAmount(ordeid, totalamount);
            db.SubmitChanges();
            lbTongTien.Text ="Tổng tiền đã tính thuế VAT và phí vận chuyển "+ totalamount.ToString("#,###,###")+"VNĐ";
            lblThongBao.Text = "Thành công";
            
        }
        catch
        {
            lblThongBao.Text = "Thất bại";
        }
    }
}
